//
//  UIView+CLCategory.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2021/7/10.
//

#import "UIView+CLCategory.h"
#import <objc/runtime.h>

typedef void(^_LayoutSubViewBlock)(CGRect);

/// 辅助view，用于布局，内部用
@interface CLPrivateLayoutView : UIView

@property (nonatomic, strong) NSMutableArray *layoutSubViewsBlocks;

/// 返回值用于取消监听
- (void(^)(void))addSubLayoutBlock:(_LayoutSubViewBlock)block;

@end

@implementation CLPrivateLayoutView

- (void)layoutSubviews {
    [super layoutSubviews];
    for (_LayoutSubViewBlock block in self.layoutSubViewsBlocks) {
        block(self.bounds);
    }
}

- (void(^)(void))addSubLayoutBlock:(_LayoutSubViewBlock)block {
    [self.layoutSubViewsBlocks addObject:block];
    
    return ^() {
        [self.layoutSubViewsBlocks removeObject:block];
    };
}

- (NSMutableArray *)layoutSubViewsBlocks {
    if (_layoutSubViewsBlocks == nil) {
        _layoutSubViewsBlocks = [NSMutableArray array];
    }
    return _layoutSubViewsBlocks;
}

@end
@implementation UIView (CLCategory)

/**
 按钮的圆角设置
 
 @param corners UIRectCorner要切除的圆角
 @param cornerRadius 圆角半径
 */
- (void)cl_setPartRoundCorners:(UIRectCorner)corners cornerRadius:(float)cornerRadius {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)].CGPath;
    self.layer.mask = shapeLayer;
}

- (void)cl_setPartRoundCorners:(UIRectCorner)corners cornerRadius:(float)cornerRadius atSize:(CGSize)size {
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:(CGRect){0,0,size} byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)].CGPath;
    self.layer.mask = shapeLayer;
}

/// 添加圆角view（不会触发离屏渲染，使用CAShapeLayer图层实现，layer会随view变化而变化，多次调用不会重复添加图层）
- (CAShapeLayer *)cl_addRoundedCorners:(UIRectCorner)corners withRadii:(CGSize)radii color:(UIColor *)color {
    CLPrivateLayoutView *layoutView = self.p_cl_layoutView;
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.fillColor = color.CGColor;
    layer.borderWidth = 0;
    [layoutView.layer addSublayer:layer];
    [layoutView addSubLayoutBlock:^(CGRect bounds) {
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:corners cornerRadii:radii];
        layer.frame = bounds;
        layer.path = maskPath.CGPath;
    }];
    return layer;
}

/// 添加渐变layer（layer大小会随view变化而变化，没有去重，避免重复添加）
- (void)cl_addSameSizeGradientLayer:(NSArray *)colors
                          locations:(NSArray *)locations
                         startPoint:(CGPoint)startPoint
                           endPoint:(CGPoint)endPoint
                       cornerRadius:(CGFloat)cornerRadius {
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.colors = colors;
    gradientLayer.locations = locations;
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    gradientLayer.cornerRadius = cornerRadius;
    
    CLPrivateLayoutView *layoutView = self.p_cl_layoutView;
    [layoutView.layer addSublayer:gradientLayer];
    [layoutView addSubLayoutBlock:^(CGRect bounds) {
        gradientLayer.frame = bounds;
    }];
}

/// 添加layer（layer大小会随view变化而变化，没有去重，避免重复添加）
- (void)cl_addSameSizeLayer:(CALayer * _Nonnull)layer {
    CLPrivateLayoutView *layoutView = self.p_cl_layoutView;
    [layoutView.layer addSublayer:layer];
    [layoutView addSubLayoutBlock:^(CGRect bounds) {
        layer.frame = bounds;
    }];
}

/// 内部view辅助布局
- (CLPrivateLayoutView *)p_cl_layoutView {
    CLPrivateLayoutView *cornerRadiusView = objc_getAssociatedObject(self, _cmd);
    if (cornerRadiusView == nil) {
        cornerRadiusView = [[CLPrivateLayoutView alloc] init];
        cornerRadiusView.userInteractionEnabled = NO;
        objc_setAssociatedObject(self, _cmd, cornerRadiusView, OBJC_ASSOCIATION_RETAIN);
        [self addSubview:cornerRadiusView];
        [cornerRadiusView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return cornerRadiusView;
}

- (UIView *)cl_addBottomSeparatorLineWithColor:(UIColor *)color height:(CGFloat)height {
    return [self cl_addBottomSeparatorLineWithColor:color height:height leftMargin:0 rightMargin:0 bottomMargin:0];
}

- (UIView *)cl_addBottomSeparatorLineWithColor:(UIColor *)color height:(CGFloat)height leftMargin:(CGFloat)leftMargin rightMargin:(CGFloat)rightMargin bottomMargin:(CGFloat)bottomMargin{
    UIView * separatorLine = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, CGRectGetHeight(self.bounds) - height - bottomMargin, CGRectGetWidth(self.bounds) - leftMargin - rightMargin, height)];
    separatorLine.backgroundColor = color;
    [self addSubview:separatorLine];
    return separatorLine;
}
@end
